package cn.itcast.controller;

import cn.itcast.entity.Result;
import cn.itcast.massage.MessageConstant;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/getCurrentLoginUser")
    public Result getCurrentLoginUser(){
        //由于登录操作是SpringSecurity完成的, 我们获取当前登录用户, 需要借助于SpringSecurity提供的API;
        User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user != null){
            Map map = new HashMap();
            map.put("username",user.getUsername());
            Set<String> auths = AuthorityUtils.authorityListToSet(user.getAuthorities());
            map.put("auths",auths);
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,map);
        }
        return new Result(false,MessageConstant.GET_USERNAME_FAIL);
    }
}
